package com.zq.aop;

import com.zq.annotation.CheckPermission;
import com.zq.annotation.CheckRoles;
import com.zq.exception.NoSuchPermissionException;
import com.zq.exception.NoSuchRolesException;
import com.zq.verify.Verify;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.adapter.AdvisorAdapter;

import java.lang.reflect.Method;

/**
 * 自定义前置AOP
 */
public class VerifyBeforeAdvice implements MethodBeforeAdvice,  AdvisorAdapter {

    private Verify verify;


    public void setVerify(Verify verify) {
        this.verify = verify;
    }

    @Override
    public void before(Method method, Object[] args, Object target) {
        final CheckRoles rolesAnnotation = method.getAnnotation(CheckRoles.class);
        final CheckPermission permissionAnnotation = method.getAnnotation(CheckPermission.class);
        if(rolesAnnotation!=null&&
                !verify.verifyRoles(rolesAnnotation.value(), rolesAnnotation.type()))
            throw new NoSuchRolesException(rolesAnnotation.msg());
        if(permissionAnnotation!=null&&
                !verify.verifyPermissions(permissionAnnotation.value(), permissionAnnotation.type()))
            throw new NoSuchPermissionException(permissionAnnotation.msg());
    }

    @Override
    public boolean supportsAdvice(Advice advice) {
        return true;
    }

    @Override
    public MethodInterceptor getInterceptor(Advisor advisor) {
        return null;
    }
}

